package 复杂度;

/**
 * @author 冷加宝
 * @version 1.0
 */
public class complexity {
    public static void bubbleSort(int[] arr){
        if(arr == null || arr.length < 2){
            return;
        }
        int end = arr.length-1, i = 0;
        while(end > 0){
            if(arr[i] > arr[i+1]){
                swap(arr, i, i+1);
            }
            if(i == end-1){
                i = 0;
                end--;
            }else{
                i++;
            }
        }
    }

    public static void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
        // 随机生成长度为n
        // 值在0~v-1之间
        // 且任意相邻两数不相等的数组
        int n = 10, v = 4;
        int[] arr2 = new int[n];
        arr2[0] = (int)(Math.random() * v);
        for(int i = 1; i < n; i++){
            do{
                arr2[i] = (int)(Math.random() * v);
            }while(arr2[i] == arr2[i-1]);
        }
        for (int arr : arr2) {
            System.out.print(" " + arr + " ");
        }
        System.out.println();
        System.out.println("----------------------------------------------");

        int[] arr = { 64, 31, 78, 0, 5, 7, 103 };
        bubbleSort(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
        System.out.println("===================================================");

        int N = 300000;
        long start;
        long end;
        System.out.println("测试开始");
        start = System.currentTimeMillis();
        for (int i = 1; i <= N; i++) {
            for (int j = i; j <= N; j += i) {
                // 这两个嵌套for循环的流程，时间复杂度为O(N * logN)
                // 1/1 + 1/2 + 1/3 + 1/4 + 1/5 + ... + 1/n，也叫"调和级数"，收敛于O(logN)
                // 所以如果一个流程的表达式 : n/1 + n/2 + n/3 + ... + n/n
                // 那么这个流程时间复杂度O(N * logN)
            }
        }
        end = System.currentTimeMillis();
        System.out.println("测试结束，运行时间 : " + (end - start) + " 毫秒");

        System.out.println("测试开始");
        start = System.currentTimeMillis();
        for (int i = 1; i <= N; i++) {
            for (int j = i; j <= N; j++) {
                // 这两个嵌套for循环的流程，时间复杂度为O(N^2)
                // 很明显等差数列
            }
        }
        end = System.currentTimeMillis();
        System.out.println("测试结束，运行时间 : " + (end - start) + " 毫秒");
    }
}
